//
//  CXPhotoBrowser.swift
//  Asman
//
//  Created by 李旭峰 on 6/4/19.
//  Copyright © 2019 李旭峰. All rights reserved.
//

import UIKit
import Alamofire

class CXPhotoBrowser: UIView {
    var currentIndex:Int = 0
    var currentCell:CXPhotoAssetCell?
    var picAssets:[CXPhotoAsset] = []
    lazy var customNavigationView:UIView = {
        let tempView = UIView()
        tempView.backgroundColor = UIColor.clear
        return tempView
    }()
    lazy var btnClose:CXPowerButton = {
        let btn = CXPowerButton(type: .image)
        btn.addTarget(self, action: #selector(onClickedCloseButton), for: .touchUpInside)
        btn.iconLabel.openShadow = true
        // TODO:>
        //        btn.iconLabel.cxFont = FontAsset.Icon.size(24.0)
        btn.iconLabel.cxFont = FontAsset.PingFangSC_Regular.size(12)
        btn.setIcon("\u{e702}", for: .normal)
        btn.setIconColor(UIColor.white, for: .normal)
        btn.paddingValue = UIEdgeInsets(top: 15.0, left: 15.0, bottom: 15.0, right: 15.0)
        return btn
    }()
    lazy var titleLabel:CXLabel = {
        let lb = CXLabel()
        lb.openShadow = true
        lb.cxFont = FontAsset.PingFangSC_Regular.size(18.0)
        lb.cxTextColor = UIColor.white
        lb.textAlignment = .center
        return lb
    }()
    lazy var indexLabel:CXLabel = {
        let lb = CXLabel()
        lb.cxTextColor = UIColor(hexStr: "#FFFFFF", alpha: 1.0)
        lb.openShadow = true
        lb.cxFont = FontAsset.PingFangSC_Semibold.size(16.0)
        lb.textAlignment = .right
        return lb
    }()
    lazy var collectionView:UICollectionView = {
        let config = UICollectionViewFlowLayout()
        config.itemSize = self.bounds.size
        config.minimumLineSpacing = 0
        config.minimumInteritemSpacing = 0
        config.sectionInset = UIEdgeInsets.zero
        config.scrollDirection = UICollectionView.ScrollDirection.horizontal
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: config)
        collectionView.register(CXPhotoAssetCell.self, forCellWithReuseIdentifier: NSStringFromClass(CXPhotoAssetCell.self))
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.isPrefetchingEnabled = true
        collectionView.isPagingEnabled = true
        collectionView.decelerationRate = UIScrollView.DecelerationRate.fast
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()

    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        self.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { (make) in
            make.centerX.width.equalToSuperview()
            make.top.height.equalToSuperview()
        }

        self.addSubview(self.customNavigationView)
        self.customNavigationView.snp.makeConstraints { (make) in
            make.centerX.width.equalToSuperview()
            make.top.equalToSuperview().offset(vSafeTop)
            make.height.equalTo(44.0)
        }
        self.customNavigationView.addSubview(self.btnClose)
        self.customNavigationView.addSubview(self.indexLabel)
        self.customNavigationView.addSubview(self.titleLabel)
        self.btnClose.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.leading.equalToSuperview().offset(20.0)
        }
        self.indexLabel.snp.makeConstraints { (make) in
            make.trailing.equalToSuperview().offset(-20.0)
            make.centerY.equalToSuperview()
        }
        self.titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(0.75)
            make.centerY.equalToSuperview()
        }
        self.collectionView.reloadData()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        self.collectionView.scrollToItem(at: IndexPath(row: self.currentIndex, section: 0), at: UICollectionView.ScrollPosition.left, animated: false)
        let assetItem = self.picAssets[self.currentIndex]
        if assetItem.title.count >= 1 {
            self.indexLabel.snp.remakeConstraints { (make) in
                make.centerY.equalToSuperview()
                make.trailing.equalToSuperview().offset(-20.0)
            }
            self.titleLabel.isHidden = false
            self.titleLabel.cxText = assetItem.title
        }else{
            self.indexLabel.snp.remakeConstraints { (make) in
                make.centerY.equalToSuperview()
                make.centerX.equalToSuperview()
            }
            self.titleLabel.isHidden = true
            self.titleLabel.cxText = assetItem.title
        }
        self.indexLabel.cxText = "\(self.currentIndex + 1)/\(self.picAssets.count)"
    }
    //    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    //        self.removeFromSuperview()
    //    }
    func show(){
        let window = UIApplication.shared.keyWindow
        self.frame = window?.bounds ?? CGRect.zero
        window?.addObserver(self, forKeyPath: "frame", options: [.new], context: nil)
        window?.addSubview(self)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "frame",let tempView = object as? UIView {
            self.frame = tempView.bounds
        }
    }
    @objc func onClickedCloseButton(){
        self.removeFromSuperview()
    }
}
extension CXPhotoBrowser : UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.picAssets.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(CXPhotoAssetCell.self), for: indexPath) as! CXPhotoAssetCell
        cell.setSingTapAction {[weak self] in
            guard let `self` = self else { return }
        //          self.removeFromSuperview()
        }
        cell.setupPhotoAsset(self.picAssets[indexPath.row])
        cell.delegate = self
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: self.collectionView.bounds.width, height: self.collectionView.bounds.height)
    }
}
extension CXPhotoBrowser : UIScrollViewDelegate {
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        let cell = self.collectionView.visibleCells.first
        if let assetCell = cell as? CXPhotoAssetCell {
            assetCell.pause()
        }
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.perform(#selector(didEndDecelerating), with: nil, afterDelay: 0)
    }
    @objc func didEndDecelerating() {
        if let index = self.collectionView.indexPathsForVisibleItems.first {
            self.currentIndex = index.row
            let assetItem = self.picAssets[self.currentIndex]
            self.titleLabel.cxText = assetItem.title
            self.indexLabel.cxText = "\(self.currentIndex + 1)/\(self.picAssets.count)"
        }
    }
}
extension CXPhotoBrowser : CXPhotoAssetCellDelegate {
    func save(_ cell: CXPhotoAssetCell, withAsset asset: CXPhotoAsset) {

    }

    func save(_ cell: CXPhotoAssetCell, withImagePath imagePath: String) {
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)

        // change the style sheet text color
        alert.view.tintColor = UIColor(hexStr: "#007AFF", alpha: 1.0)

        let actionCancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        let actionCamera = UIAlertAction.init(title: "保存到相册", style: .default) {[weak self] (UIAlertAction) -> Void in
            guard let `self` = self else { return }
            self.showLoading()
            UIImage.download(imagePath) {[weak self] (image, error) in
                guard let tempImage = image else { return }
                tempImage.saveImageToAlbum {[weak self] (navitePath, error) in
                    guard let `self` = self else { return }
                    self.hiddenLoading()
                    if error == nil {
                        CXMBShow.showMessage("保存成功")
                    }else {
                        CXMBShow.showMessage("保存失败，请重试")
                    }
                }
            }
        }
        alert.addAction(actionCancel)
        alert.addAction(actionCamera)
        UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
    }

    func save(_ cell: CXPhotoAssetCell, withImage image: UIImage) {
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)

        // change the style sheet text color
        alert.view.tintColor = UIColor(hexStr: "#007AFF", alpha: 1.0)

        let actionCancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        let actionCamera = UIAlertAction.init(title: "保存到相册", style: .default) {[weak self] (UIAlertAction) -> Void in
            guard let `self` = self else { return }
            self.showLoading()
            image.saveImageToAlbum { (imgPath, error) in
                self.hiddenLoading()
                if error == nil {
                    CXMBShow.showMessage("保存成功")
                }else {
                    CXMBShow.showMessage("保存失败，请重试")
                }
            }
        }
        alert.addAction(actionCancel)
        alert.addAction(actionCamera)
        UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
    }

    func save(_ cell: CXPhotoAssetCell, withVideoPath videoPath: String) {
        let alert = UIAlertController.init(title: nil, message: nil, preferredStyle: .actionSheet)
        // change the style sheet text color
        alert.view.tintColor = UIColor(hexStr: "#007AFF", alpha: 1.0)
        let actionCancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
        let actionCamera = UIAlertAction.init(title: "保存到相册", style: .default) {[weak self] (UIAlertAction) -> Void in
            guard let `self` = self else { return }
            guard let tempVideoPathUrl = URL(string: videoPath) else { return }
            self.showLoading()
//            Alamofire.download(tempVideoPathUrl) { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
//                let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
//                let videoName = UUID.init().uuidString.uppercased()
//                let fileURL = documentsURL.appendingPathComponent("\(videoName).mp4")
//                return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
//            }.downloadProgress { (progress) in
//
//            }.response {[weak self] (response) in
//                guard let `self` = self else { return }
//                if response.error != nil {
//                    self.hiddenLoading()
//                    CXMBShow.showMessage("下载失败，请重试")
//                    return
//                }
//                guard let tempDestinationUrl = response.destinationURL else {
//                    self.hiddenLoading()
//                    CXMBShow.showMessage("下载失败，请重试")
//                    return
//                }
//                let vc = (UIApplication.shared.keyWindow?.rootViewController)!
//                SaveToAlbum.shared.saveFileVideo(_videoPath: tempDestinationUrl.absoluteString, _viewCom: vc) {[weak self] (isSuccess) in
//                    guard let `self` = self else { return }
//                    self.hiddenLoading()
//                    if isSuccess {
//                        CXMBShow.showMessage("保存成功")
//                    }else {
//                        CXMBShow.showMessage("保存失败")
//                    }
//                }
//            }
            AF.download(tempVideoPathUrl,to: { (url, response) -> (destinationURL: URL, options: DownloadRequest.Options) in
                let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
                let videoName = UUID.init().uuidString.uppercased()
                let fileURL = documentsURL.appendingPathComponent("\(videoName).mp4")
                return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
            }).downloadProgress{ (progress) in
                print(progress)
            }.response(queue: DispatchQueue.global(qos: .utility)) {[weak self] (response) in
                guard let `self` = self else { return }
                if response.error != nil {
                    self.hiddenLoading()
                    CXMBShow.showMessage("下载失败，请重试")
                    return
                }
                guard let tempDestinationUrl = response.fileURL else {
                    self.hiddenLoading()
                    CXMBShow.showMessage("下载失败，请重试")
                    return
                }
                let vc = (UIApplication.shared.keyWindow?.rootViewController)!
                SaveToAlbum.shared.saveFileVideo(_videoPath: tempDestinationUrl.absoluteString, _viewCom: vc) {[weak self] (isSuccess) in
                    guard let `self` = self else { return }
                    self.hiddenLoading()
                    if isSuccess {
                        CXMBShow.showMessage("保存成功")
                    }else {
                        CXMBShow.showMessage("保存失败")
                    }
                }
            }
        }
        alert.addAction(actionCancel)
        alert.addAction(actionCamera)
        UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
    }
    
    func showLoading(){
        self.cx_showLoading()
    }
    func hiddenLoading(){
        self.cx_removeLoading()
    }
}
